﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using Model;

namespace TanHungLong
{
    public partial class FrmHoaDonBan : DevExpress.XtraEditors.XtraForm
    {
        #region variant
        private bool allowCloseForm = true;
        private GiaBOCollection giaBOCollection = null;
        private NhomHangBOCollection nhomHangBOCollection = null;
        private HoaDonBanBOCollection HoaDonBanBOCollection = null;
        private HoaDonBanChiTietBOCollection HoaDonBanChiTietBOCollection = HoaDonBanChiTietBOCollection.NewHoaDonBanChiTietBOCollection();
        private HoaDonBanBO HoaDonBanBO = HoaDonBanBO.NewRootHoaDonBanBO();
        private RMaVachBOCollection rMaVachBOColl = RMaVachBOCollection.NewRMaVachBOCollection();
        #endregion variant

        //=====================================
        #region form
        public FrmHoaDonBan()
        {
            InitializeComponent();
            this.KeyPreview = true;

            this.Load += new EventHandler(FrmHoaDonBan_Load);
            this.Shown += new EventHandler(FrmHoaDonBan_Shown);
            this.FormClosing += new FormClosingEventHandler(FrmHoaDonBan_FormClosing);

            this.btnAdd.Click += new EventHandler(btnAdd_Click);
            this.btnXoa.Click += new EventHandler(btnDelete_Click);
            this.btnRefresh.Click += new EventHandler(btnRefresh_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.btnClose.Click += new EventHandler(btnClose_Click);
            this.btnRefreshMatHang.Click += new EventHandler(btnRefreshMatHang_Click);

            this.btnThanhToan.Click += new EventHandler(toolStripMenuItemThanhToan_Click);
            this.btnDelHoaDon.Click += new EventHandler(btnDelete_Click);

            this.grdViewMatHang.DoubleClick += new System.EventHandler(this.grdViewMatHang_DoubleClick);
            this.gridViewHoaDonBan.RowCellClick += new RowCellClickEventHandler(this.gridViewHoaDonBan_RowCellClick);

            this.grdViewMatHang.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);
            this.grdViewHoaDonBanChiTiet.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);

            this.grdViewMatHang.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);
            this.grdViewHoaDonBanChiTiet.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);

            this.txtTimkiem.KeyDown += new KeyEventHandler(this.txtTimkiem_KeyDown);
            this.grdViewMatHang.KeyDown += new KeyEventHandler(this.grdViewMatHang_KeyDown);
            this.reTextMaVach.KeyDown += new KeyEventHandler(reTextMaVach_KeyDown);
            this.KeyDown += new KeyEventHandler(FrmHoaDonBan_KeyDown);
            this.lookUpMaKhachHang.EditValueChanged += new EventHandler(lookUpMaKhachHang_EditValueChanged);

            this.lookUpEditKhachHang.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(lookUpEditKhachHang_ButtonClick);
        }


        void lookUpMaKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            lookUpEditKhachHang.EditValue = lookUpMaKhachHang.EditValue;
        }

        void FrmHoaDonBan_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
                int _idMatHang = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("MatHangID"), -1);
                int _idDonViTinh = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("DonViTinhID"), -1);

                if ((_idMatHang >= 0) & (_idDonViTinh >= 0))
                {
                    DeleteMatHang(_idMatHang, _idDonViTinh);
                }
                else
                {
                    MessageBox.Show("Bạn chưa chọn Vật tư để xóa! Vui lòng chọn lại", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.grdViewHoaDonBanChiTiet.Focus();
                }
            }

            if (e.KeyCode == Keys.N && Control.ModifierKeys == Keys.Control)
                AddNew();
            if ((e.KeyCode == Keys.Q && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F10))
                this.Close();
            if ((e.KeyCode == Keys.R && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F5))
                RefreshData();
            if ((e.KeyCode == Keys.S && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F6))
                Save();
            if ((e.KeyCode == Keys.T && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F2))
                toolStripMenuItemThanhToan_Click(null, null);
            if ((e.KeyCode == Keys.Delete && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F8))
                btnDelete_Click(null, null);
        }

        private void FrmHoaDonBan_Shown(object sender, EventArgs e)
        {
            this.lookUpEditKhachHang.Focus();
        }

        private void FrmHoaDonBan_Load(object sender, EventArgs e)
        {
            dtNgayLapHoaDon.DateTime = Session.NgayHeThong;

            Utility.InitControl(this.reLookUpMatHangID);
            Utility.InitControl(this.reLookUpDonViTinhID);

            Utility.InitControl(this.reLookUpMatHang);
            Utility.InitControl(this.reLookUpDonViTinh);
            Utility.InitControl(this.reLookUpDMKhoID);

            //Utility.InitControl(this.lookUpEditKhachHang);

            Utility.InitControl(this.reLookUpKhachHangID);

            this.grdView.FocusedRowChanged += new FocusedRowChangedEventHandler(grdView_FocusedRowChanged);
            this.txtTimkiem.EditValueChanged += new System.EventHandler(this.txtTimkiem_EditValueChanged);

            this.spinEditPhucVu.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditGiamGia.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditChietKhau.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditVAT.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditTienPhatSinh.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.grdViewHoaDonBanChiTiet.CellValueChanged += new CellValueChangedEventHandler(this.grdViewHoaDonBanChiTiet_CellValueChanged);

            RefreshData();
        }

        private void FrmHoaDonBan_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.allowCloseForm == false)
                e.Cancel = true;
        }

        #endregion form

        //=====================================
        #region control
        private void txtTimkiem_EditValueChanged(object sender, EventArgs e)
        {
            FilterMatHangByName(txtTimkiem.Text.Trim());
        }

        private void spinEditTienPhatSinh_ValueChanged(object sender, EventArgs e)
        {
            TinhTien();
        }


        void lookUpEditKhachHang_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                FrmNewKhachHang.daluu = 0;
                FrmNewKhachHang frNewKH = new FrmNewKhachHang();
                frNewKH.ShowDialog();
                if (FrmNewKhachHang.daluu == 1)
                {
                    KhachHangBOCollection nn = KhachHangBOCollection.GetKhachHangBOCollection("KH = 1");
                    bdSourceKhachHang.DataSource = nn.Clone();
                    lookUpEditKhachHang.EditValue = lookUpMaKhachHang.EditValue = StaticUtil.GetInt(FrmNewKhachHang.KhachHangBO.KhachHangID, -1);
                    FrmNewKhachHang.daluu = 0;
                }
            }
            else
                if (e.Button.Index == 2)
                    lookUpEditKhachHang.EditValue = null;
        }
        #endregion control

        //=====================================
        #region button
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnRefreshMatHang_Click(object sender, EventArgs e)
        {
            FilterMatHangByName("");
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddNew();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int _HoaDonBanID = StaticUtil.GetInt(this.HoaDonBanBO.HoaDonBanID, -1);

            if (_HoaDonBanID != -1)
            {
                if (MessageBox.Show("Bạn muốn xóa Hóa đơn Bán hàng này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Model.HoaDonBanBO.DeleteHoaDonBanBO(_HoaDonBanID);

                    for (int k = 0; k < HoaDonBanChiTietBOCollection.Count; k++)
                    {
                        HoaDonBanChiTietBO.DeleteHoaDonBanChiTietBO((int)HoaDonBanChiTietBOCollection[k].HoaDonBanChiTietID);
                    }

                    RefreshData();
                    btnAdd_Click(e, e);
                }
            }
            else
            {
                MessageBox.Show("Chưa chọn Hóa đơn Bán hàng để xóa! ", "Thông báo", MessageBoxButtons.OK);
            }
        }

        private void btnThanhToan_Click(object sender, EventArgs e)
        {
            int _HoaDonBanID = StaticUtil.GetInt(this.HoaDonBanBO.HoaDonBanID, -1);

            if (_HoaDonBanID >= 0 && this.HoaDonBanBO != null)
            {
                FrmThuHoaDon frmThuHoaDon = new FrmThuHoaDon((FrmMain)this.ParentForm, this.HoaDonBanBO, this.HoaDonBanChiTietBOCollection);
                frmThuHoaDon.OnCompleted += new OnCompletedEventHandler(frmThuHoaDon_OnCompleted);
                frmThuHoaDon.Show();
            }
            else
                MessageBox.Show("Chưa chọn Hóa đơn Bán hàng để Thu tiền! ", "Thông báo", MessageBoxButtons.OK);
        }
        #endregion button

        //=====================================
        #region grid
        private void grdView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            FilterMatHang();
        }

        private void grdView_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView grdView = (GridView)sender;

            bool del = StaticUtil.GetBool(grdView.GetFocusedRowCellValue("DELE"));
            string fieldName = grdView.FocusedColumn.FieldName;

            if (del && fieldName != "DELE")
                e.Cancel = true;
            else
                if (fieldName == "DELE" && grdView.FocusedRowHandle == GridControl.NewItemRowHandle)
                    e.Cancel = true;
        }

        private void grdView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            bool del = StaticUtil.GetBool(this.grdViewMatHang.GetRowCellValue(e.RowHandle, "DELE"));

            if (del)
            {
                e.Appearance.Font = MyStyle.DELETE_FONT;
                e.Appearance.ForeColor = MyStyle.DELETE_COLOR;
            }
        }

        private void grdViewMatHang_DoubleClick(object sender, EventArgs e)
        {
            UpdateHoaDonBan();
        }

        private void gridViewHoaDonBan_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            int HoaDonBanID = StaticUtil.GetInt(gridViewHoaDonBan.GetFocusedRowCellValue("HoaDonBanID"));
            this.HoaDonBanBO = Model.HoaDonBanBO.GetRootHoaDonBanBO(HoaDonBanID);
            this.HoaDonBanChiTietBOCollection = Model.HoaDonBanChiTietBOCollection.GetHoaDonBanChiTietBOCollection("HoaDonBanID = " + HoaDonBanID.ToString());

            lookUpEditKhachHang.EditValue = HoaDonBanBO.KhachHangID.Value;
            txtMaSo.Text = HoaDonBanBO.MaSo;
            txtNoidung.Text = HoaDonBanBO.NoiDung;
            txtGhichu.Text = HoaDonBanBO.GhiChu;
            dtNgayLapHoaDon.DateTime = HoaDonBanBO.NgayLapHoaDon.Value;

            spinEditVAT.Value = (decimal)HoaDonBanBO.MucVAT;
            spinEditChietKhau.Value = (decimal)HoaDonBanBO.MucChietKhau;
            spinEditPhucVu.Value = (decimal)HoaDonBanBO.MucPhucVu;
            spinEditGiamGia.Value = (decimal)HoaDonBanBO.MucGiamGia;
            spinEditTienPhatSinh.Value = (decimal)HoaDonBanBO.TienPhatSinh;
            txtLyDoPhatSinh.Text = HoaDonBanBO.LyDoPhatSinh;

            bdSourceHoaDonBanChiTiet.DataSource = HoaDonBanChiTietBOCollection.Clone();

            sapxep();
            TinhTien();
        }

        private void grdViewHoaDonBanChiTiet_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                int _idMatHang = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("MatHangID"));
                int _idDonViTinh = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("DonViTinhID"));
                double _soLuong = StaticUtil.GetDouble(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("SoLuong"));
                double _giaBan = StaticUtil.GetDouble(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("DonGia"));

                int kiemtraID = this.HoaDonBanChiTietBOCollection.CheckExits(_idMatHang, _idDonViTinh);
                double thanhtien = (double)_soLuong * (double)_giaBan;

                HoaDonBanChiTietBOCollection[kiemtraID].SoLuong = _soLuong;
                HoaDonBanChiTietBOCollection[kiemtraID].ThanhTien = thanhtien;
                sapxep();
                TinhTien();
            }
            catch { }
        }
        #endregion grid

        //=====================================
        #region function
        private void FilterMatHang()
        {
            Session.NhomHangID = StaticUtil.GetRealInt(this.grdView.GetFocusedRowCellValue("NhomHangID"));
            TonKhoBOCollection tonKhoBOCollection = TonKhoBOCollection.GetTonKhoBOCollection();

            if (Session.NhomHangID == -1)
            {
                this.giaBOCollection = GiaBOCollection.GetGiaBOCollection();

                #region Lấy giá cả và tồn kho của mặt hàng
                int recordCount = this.giaBOCollection.Count;
                if (recordCount > 0)
                {
                    for (int i = 0; i < recordCount; i++)
                    {
                        this.giaBOCollection[i].Ten = ImPortTonKho2Gia(StaticUtil.GetInt(this.giaBOCollection[i].MatHangID, -1), StaticUtil.GetInt(this.giaBOCollection[i].DonViTinhID, -1), tonKhoBOCollection).ToString();
                    }
                }
                #endregion

                this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            }
            else
            {
                MatHangBOCollection matHangBOCollection = MatHangBOCollection.GetMatHangBOCollection("NhomHangID = " + Session.NhomHangID.ToString());
                string strWhere = "";
                string listID = "";
                int recordCount = matHangBOCollection.Count;
                if (recordCount > 0)
                {
                    for (int i = 0; i < recordCount; i++)
                    {
                        object _idVattu = matHangBOCollection[i].MatHangID;
                        listID += _idVattu.ToString() + ",";
                    }
                }

                strWhere = strWhere + " MatHangID in ('" + listID.Replace(",", "','") + "')";
                this.giaBOCollection = GiaBOCollection.GetGiaBOCollection(strWhere);

                #region Lấy giá cả và tồn kho của mặt hàng
                int recordCount1 = this.giaBOCollection.Count;
                if (recordCount1 > 0)
                {
                    for (int i = 0; i < recordCount1; i++)
                    {
                        this.giaBOCollection[i].Ten = ImPortTonKho2Gia(StaticUtil.GetInt(this.giaBOCollection[i].MatHangID, -1), StaticUtil.GetInt(this.giaBOCollection[i].DonViTinhID, -1), tonKhoBOCollection).ToString();
                    }
                }
                #endregion

                this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
            }
        }

        private void FilterMatHangByName(string nameMatHang)
        {
            MatHangBOCollection matHangBOCollection = MatHangBOCollection.GetMatHangBOCollection(" Ten like N'%" + nameMatHang + "%' or MaMatHang like N'%" + nameMatHang + "%'");
            string strWhere = "";
            string listID = "";
            int recordCount = matHangBOCollection.Count;

            if (recordCount > 0)
            {
                for (int i = 0; i < recordCount; i++)
                {
                    object _idVattu = matHangBOCollection[i].MatHangID;
                    listID += _idVattu.ToString() + ",";
                }
            }

            strWhere = strWhere + " MatHangID in ('" + listID.Replace(",", "','") + "')";
            this.giaBOCollection = GiaBOCollection.GetGiaBOCollection(strWhere);
            this.bdSourceGia.DataSource = this.giaBOCollection.Clone();
        }

        private void ResetData()
        {
            lookUpEditKhachHang.EditValue = null;
            lookUpMaKhachHang.EditValue = null;
            dtNgayLapHoaDon.DateTime = Session.NgayHeThong;
            txtMaSo.Text = "BH-" + Session.NgayHeThong.ToString("dd/MM/yyyy") + "-" + DateTime.Now.ToString("HH:mm:ss");
            txtGhichu.Text = "";
            txtNoidung.Text = "";
            txtLyDoPhatSinh.Text = "";
            spinEditChietKhau.Value = spinEditGiamGia.Value = spinEditPhucVu.Value = spinEditVAT.Value = spinEditTienPhatSinh.Value = 0;

            this.HoaDonBanBO = Model.HoaDonBanBO.NewRootHoaDonBanBO();
            this.HoaDonBanChiTietBOCollection = Model.HoaDonBanChiTietBOCollection.NewHoaDonBanChiTietBOCollection();
            bdSourceHoaDonBanChiTiet.DataSource = this.HoaDonBanChiTietBOCollection.Clone();
            sapxep();
            TinhTien();
        }

        private void RefreshData()
        {
            #region

            DanhMucBOList donViTinhBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DonViTinh);
            Utility.SetData(this.reLookUpDonViTinh, donViTinhBOList, donViTinhBOList.Count);
            Utility.SetData(this.reLookUpDonViTinhID, donViTinhBOList, donViTinhBOList.Count);

            DanhMucBOList dmKhoBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DanhMucKho);
            Utility.SetData(this.reLookUpDMKhoID, dmKhoBOList, dmKhoBOList.Count);

            MatHangBOList matHangBOList = MatHangBOList.GetMatHangBOList();
            Utility.SetData(this.reLookUpMatHang, matHangBOList, matHangBOList.Count);
            Utility.SetData(this.reLookUpMatHangID, matHangBOList, matHangBOList.Count);

            KhachHangBOList khachHangBOList = KhachHangBOList.GetKhachHangBOList("KH = 1");
            Utility.SetData(this.reLookUpKhachHangID, khachHangBOList, khachHangBOList.Count);

            KhachHangBOCollection khachHangBOColl = KhachHangBOCollection.GetKhachHangBOCollection("KH = 1");
            bdSourceKhachHang.DataSource = khachHangBOColl.Clone();
            #endregion BOList

            this.HoaDonBanBOCollection = Model.HoaDonBanBOCollection.GetHoaDonBanBOCollection(" (ThanhToan = 0 and TinhTrangThanhToan = 0 and TinhTrangXuatKho = 0 and (convert(nvarchar,NgayLapHoaDon,111) = '" + Session.NgayHeThong.ToString("yyyy/MM/dd") + "') and USRC = " + Session.LoginID.ToString() + ") or ( ThucHien = 1 " + " and USRC = " + Session.LoginID.ToString() + ")");
            this.nhomHangBOCollection = NhomHangBOCollection.GetNhomHangBOCollection();

            NhomHangBO NewNhomHangBO = NhomHangBO.NewRootNhomHangBO();
            NewNhomHangBO.Ten = "Tất cả";
            NewNhomHangBO.NhomHangID = -1;
            this.nhomHangBOCollection.Add(NewNhomHangBO);

            this.bdSourceNhomHang.DataSource = this.nhomHangBOCollection.Clone();
            this.bdSourceHoaDonBan.DataSource = this.HoaDonBanBOCollection.Clone();

            this.bdSourceGia.DataSource = this.giaBOCollection.Clone();

            ResetData();

            FilterMatHang();
        }

        private void AddNew()
        {
            RefreshData();
        }

        private void Save()
        {
            if (kiemtraLuu() == 1)
            {
                this.HoaDonBanBO.KhachHangID = StaticUtil.GetInt(lookUpEditKhachHang.EditValue);
                this.HoaDonBanBO.MaSo = txtMaSo.Text.Trim();
                this.HoaDonBanBO.NgayLapHoaDon = dtNgayLapHoaDon.DateTime;
                this.HoaDonBanBO.NoiDung = txtNoidung.Text.Trim();
                this.HoaDonBanBO.GhiChu = txtGhichu.Text.Trim();

                this.HoaDonBanBO.MucVAT = StaticUtil.GetDouble(spinEditVAT.Value);
                this.HoaDonBanBO.MucChietKhau = StaticUtil.GetDouble(spinEditChietKhau.Value);
                this.HoaDonBanBO.MucPhucVu = StaticUtil.GetDouble(spinEditPhucVu.Value);
                this.HoaDonBanBO.MucGiamGia = StaticUtil.GetDouble(spinEditGiamGia.Value);
                this.HoaDonBanBO.TienPhatSinh = StaticUtil.GetDouble(spinEditTienPhatSinh.Value);
                this.HoaDonBanBO.LyDoPhatSinh = txtLyDoPhatSinh.Text.Trim();

                this.HoaDonBanBO.TongSo = StaticUtil.GetDouble(spinEditTongSo.Value);
                this.HoaDonBanBO.ThanhTien = StaticUtil.GetDouble(spinEditThanhTien.Value);
                this.HoaDonBanBO.TienPhaiThu = StaticUtil.GetDouble(spinEditTongTien.Value);
                this.HoaDonBanBO.TienKhachTra = 0;
                this.HoaDonBanBO.BangChu = txtBangChu.Text.Trim();
                this.HoaDonBanBO.TienThua = this.HoaDonBanBO.TienKhachTra.Value - this.HoaDonBanBO.TienPhaiThu.Value;
                this.HoaDonBanBO.ThanhToan = 0;
                this.HoaDonBanBO.TinhTrangThanhToan = 0;
                this.HoaDonBanBO.TinhTrangXuatKho = 0;
                if (StaticUtil.GetInt(this.HoaDonBanBO.ThucHien, 0) != 1)
                    this.HoaDonBanBO.ThucHien = 0;

                this.HoaDonBanBO.Save();

                int recordCount = this.HoaDonBanChiTietBOCollection.Count;
                if (recordCount > 0)
                {
                    for (int i = 0; i < recordCount; i++)
                    {
                        this.HoaDonBanChiTietBOCollection[i].HoaDonBanID = this.HoaDonBanBO.HoaDonBanID.Value;
                    }

                    this.HoaDonBanChiTietBOCollection.Save();
                }

                this.HoaDonBanChiTietBOCollection = this.HoaDonBanChiTietBOCollection.Save();

                MessageBox.Show("Cập nhật thành công! ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.HoaDonBanBOCollection = Model.HoaDonBanBOCollection.GetHoaDonBanBOCollection(" (ThanhToan = 0 and TinhTrangThanhToan = 0 and TinhTrangXuatKho = 0 and (convert(nvarchar,NgayLapHoaDon,111) = '" + Session.NgayHeThong.ToString("yyyy/MM/dd") + "') and USRC = " + Session.LoginID.ToString() + ") or ( ThucHien = 1 " + " and USRC = " + Session.LoginID.ToString() + ")");
                this.bdSourceHoaDonBan.DataSource = this.HoaDonBanBOCollection.Clone();
                this.bdSourceHoaDonBanChiTiet.DataSource = this.HoaDonBanChiTietBOCollection.Clone();
            }

            FilterMatHang();
        }

        private void UpdateHoaDonBan()
        {
            int matHangID = StaticUtil.GetInt(grdViewMatHang.GetFocusedRowCellValue("MatHangID"));
            int donViTinhID = StaticUtil.GetInt(grdViewMatHang.GetFocusedRowCellValue("DonViTinhID"));
            double giaBan = StaticUtil.GetDouble(grdViewMatHang.GetFocusedRowCellValue("GiaBan"));
            int kiemtraID = this.HoaDonBanChiTietBOCollection.CheckExits(matHangID, donViTinhID);

            if (kiemtraID == -1)
            {
                HoaDonBanChiTietBO newBO = HoaDonBanChiTietBO.NewRootHoaDonBanChiTietBO();
                newBO.MatHangID = matHangID;
                newBO.TenHang = MatHangBO.GetRootMatHangBO(matHangID).Ten;
                newBO.MaVach = "0";
                newBO.DonViTinhID = donViTinhID;
                newBO.TenDonViTinh = DanhMucBO.GetRootDanhMucBO(donViTinhID).NoiDung;
                newBO.DonGia = giaBan;
                newBO.SoLuong = 1;
                newBO.ThanhTien = giaBan * newBO.SoLuong.Value;
                HoaDonBanChiTietBOCollection.Add(newBO);

                sapxep();
                TinhTien();
            }
            else
                MessageBox.Show("Mặt hàng và Đơn vị tính này đã có! ", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void sapxep()
        {
            int length = HoaDonBanChiTietBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                HoaDonBanChiTietBOCollection[i].STT0 = (i + 1);
            }

            bdSourceHoaDonBanChiTiet.DataSource = HoaDonBanChiTietBOCollection;
        }

        private void TinhTien()
        {
            double tongso = 0;
            double thanhtien = 0;
            double tongtien = 0;

            int length = HoaDonBanChiTietBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                tongso = tongso + HoaDonBanChiTietBOCollection[i].SoLuong.Value;
                thanhtien = thanhtien + HoaDonBanChiTietBOCollection[i].ThanhTien.Value;
            }

            spinEditTongSo.Value = (decimal)tongso;
            spinEditThanhTien.Value = (decimal)thanhtien;

            double mucVAT = StaticUtil.GetDouble(spinEditVAT.Value, 0);
            double tienVAT = thanhtien * mucVAT;
            spinEditTienVAT.Value = (decimal)tienVAT;
            double mucCK = StaticUtil.GetDouble(spinEditChietKhau.Value, 0);
            double tienCK = thanhtien * mucCK;
            spinEditTienChietKhau.Value = (decimal)tienCK;
            double mucGG = StaticUtil.GetDouble(spinEditGiamGia.Value, 0);
            double tienGG = thanhtien * mucGG;
            spinEditTienGiamGia.Value = (decimal)tienGG;
            double mucPV = StaticUtil.GetDouble(spinEditPhucVu.Value, 0);
            double tienPV = thanhtien * mucPV;
            spinEditTienPhucVu.Value = (decimal)tienPV;
            double TienPhatSinh = StaticUtil.GetDouble(spinEditTienPhatSinh.Value, 0);

            tongtien = thanhtien + tienVAT + TienPhatSinh - tienCK - tienGG + tienPV;
            spinEditTongTien.Value = (decimal)tongtien;
            txtBangChu.Text = VNCurrency.ToString(tongtien);
        }

        private void DeleteMatHang(int mathangID, int donvitinhID)
        {
            if (MessageBox.Show("Bạn có muốn xóa Mặt Hàng và Đơn vị tính này không? ", "Cảnh báo!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                HoaDonBanChiTietBOCollection.Remove(mathangID, donvitinhID);
                int _idHoaDonBanChiTiet = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("HoaDonBanChiTietID"), -1);

                if (_idHoaDonBanChiTiet >= 0)
                {
                    HoaDonBanChiTietBO.DeleteHoaDonBanChiTietBO(_idHoaDonBanChiTiet);
                }

                sapxep();
                TinhTien();
            }
        }

        private int kiemtraLuu()
        {
            int tempkiemtra = 1;
            string strError = "";

            if (lookUpEditKhachHang.EditValue == null)
            {
                tempkiemtra = 0;
                strError = "Chưa chọn Khách hàng";
            }

            if (txtMaSo.Text.Trim() == "")
            {
                tempkiemtra = 0;
                strError = strError + " ;Chưa nhập Mã số";
            }

            if (tempkiemtra == 0)
                MessageBox.Show(strError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            return tempkiemtra;
        }
        #endregion function

        private void toolStripMenuItemThanhToan_Click(object sender, EventArgs e)
        {
            int _HoaDonBanID = StaticUtil.GetInt(this.HoaDonBanBO.HoaDonBanID, -1);
            if (_HoaDonBanID >= 0 && this.HoaDonBanBO != null)
            {
                FrmThuHoaDon frmThuHoaDon = new FrmThuHoaDon((FrmMain)this.ParentForm, this.HoaDonBanBO, this.HoaDonBanChiTietBOCollection);
                frmThuHoaDon.OnCompleted += new OnCompletedEventHandler(frmThuHoaDon_OnCompleted);
                frmThuHoaDon.Show();
            }
            else
                MessageBox.Show("Chưa chọn Hóa đơn Bán hàng để Thu tiền! ", "Thông báo", MessageBoxButtons.OK);
        }

        private void frmThuHoaDon_OnCompleted(object sender, OnCompletedEventArgs e)
        {
            int daluu = (int)e.objectValue;
            if (daluu == 1)
                RefreshData();

            this.BringToFront();
        }

        private void txtTimkiem_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                grdViewMatHang.Focus();
            }
        }

        private void grdViewMatHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                UpdateHoaDonBan();
            }
        }

        private double ImPortTonKho2Gia(int _matHangID, int _donViTinhID, TonKhoBOCollection tonKhoBOColl)
        {
            double _soluong = 0;
            int rowCount = tonKhoBOColl.Count;
            if (rowCount > 0)
                for (int i = 0; i < rowCount; i++)
                {
                    if ((StaticUtil.GetInt(tonKhoBOColl[i].MatHangID, -1) == _matHangID) & (StaticUtil.GetInt(tonKhoBOColl[i].DonViTinhID, -1) == _donViTinhID))
                    {
                        _soluong = _soluong + StaticUtil.GetInt(tonKhoBOColl[i].SoLuongTon, -1);
                    }
                }

            return _soluong;
        }

        private void reTextMaVach_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                try
                {
                    int _idMatHang = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("MatHangID"));
                    int _idDonViTinh = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("DonViTinhID"));
                    int kiemtraID = this.HoaDonBanChiTietBOCollection.CheckExits(_idMatHang, _idDonViTinh);

                    FrmRMaVach._maVach = "";
                    FrmRMaVach._khoID = -1;
                    FrmRMaVach frm = new FrmRMaVach(_idMatHang, _idDonViTinh);
                    frm.ShowDialog();
                    HoaDonBanChiTietBOCollection[kiemtraID].MaVach = FrmRMaVach._maVach;
                    HoaDonBanChiTietBOCollection[kiemtraID].DanhMucKhoID = FrmRMaVach._khoID;
                    sapxep();
                    FrmRMaVach._maVach = "";
                    FrmRMaVach._khoID = -1;
                }
                catch { }
            }
        }
    }
}